<?php

declare(strict_types=1);

namespace App\CustHub\Model;

use App\Common\Constants\ErrorCode;
use App\CustHub\Service\CommonService;
use App\Exception\BusinessException;
use Mine\MineModel;
use function Yansongda\Supports\data_get;

/**
 * @property int $id 主键
 * @property int $main_uid 主账号id
 * @property int $uid 私域用户ID
 * @property int $corp_id 企业id
 * @property int $template_id 模板id
 * @property string $title 标题
 * @property int $template_type 1标准模板  2标签sop模板 3新客户模板  4.群模板
 * @property int $status 状态 1-执行中  2-已完成  3已关闭
 * @property int $open_out_tag 开启排除条件
 * @property int $auto_stop 客户不符合条件时自动终止
 * @property int $is_track 是否追踪
 * @property int $tirgger_type 1按性别  2加好友直接触发  3按标签触发   优先级排序用
 * @property int $track_limit 多少分钟内回复计入统计
 * @property string $return_code 退订口令
 * @property string $return_text 退订话术
 * @property array $plan 计划
 * @property int $is_return 消息退订
 * @property \Carbon\Carbon $created_at 
 * @property \Carbon\Carbon $updated_at 
 * @property int $start_day 第几天开始
 * @property int $send_type 1按客户/客户群发送   2按条件设置发送
 * @property array $crowd_ids 群ids
 * @property array $custom_ids 用户ids
 * @property string $start_time 开始时间
 * @property string $end_time 结束时间
 * @property int $send_total 总发送信息数量
 * @property int $reply_total 有效回复数量
 * @property int $custom_total 总客户数量
 * @property int $loss_total 流失数量
 * @property int $crowd_total 群数量
 * @property int $is_loop 是否循环发送
 * @property-read mixed $trigger_condition 触发条件
 * @property-read mixed $out_tag 排除标签
 * @property-read mixed $trigger_tag 触发标签
 * @property-read mixed $condition_conf 条件配置
 * @property-read mixed $robot_user_ids 
 * @property-read null|ChUser $user 
 * @property-read null|ChSopTemplate $template 
 */
class ChSop extends MineModel
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'ch_sop';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'main_uid', 'uid', 'corp_id', 'template_id', 'title', 'template_type', 'status', 'open_out_tag', 'auto_stop', 'is_track', 'tirgger_type', 'condition_conf', 'track_limit', 'return_code', 'return_text', 'plan', 'trigger_condition', 'out_tag', 'trigger_tag', 'is_return', 'created_at', 'updated_at', 'start_day', 'send_type', 'crowd_ids', 'custom_ids', 'start_time', 'end_time', 'send_total', 'reply_total', 'custom_total', 'loss_total', 'crowd_total', 'is_loop'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'main_uid' => 'integer', 'uid' => 'integer', 'corp_id' => 'integer', 'template_id' => 'integer', 'template_type' => 'integer', 'status' => 'integer', 'open_out_tag' => 'integer', 'auto_stop' => 'integer', 'is_track' => 'integer', 'tirgger_type' => 'integer', 'condition_conf' => 'array', 'track_limit' => 'integer', 'plan' => 'array', 'trigger_condition' => 'array', 'out_tag' => 'array', 'trigger_tag' => 'array', 'is_return' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime', 'start_day' => 'integer', 'send_type' => 'integer', 'crowd_ids' => 'array', 'custom_ids' => 'array', 'send_total' => 'integer', 'reply_total' => 'integer', 'custom_total' => 'integer', 'loss_total' => 'integer', 'crowd_total' => 'integer', 'is_loop' => 'integer'];

    public function getTriggerConditionAttribute()
    {
        return !empty($this->attributes['trigger_condition'])?json_decode($this->attributes['trigger_condition'],true):[];
    }

    public function getOutTagAttribute()
    {
        return !empty($this->attributes['out_tag'])?json_decode($this->attributes['out_tag'],true):[];
    }

    public function getTriggerTagAttribute()
    {
        return !empty($this->attributes['trigger_tag'])?json_decode($this->attributes['trigger_tag'],true):[];
    }

    public function getConditionConfAttribute()
    {
        return !empty($this->attributes['condition_conf'])?json_decode($this->attributes['condition_conf'],true):[];
    }

    public function getRobotUserIdsAttribute()
    {
        return !empty($this->attributes['robot_ids'])?json_decode($this->attributes['robot_ids'],true):[];
    }

    public function user()
    {
        return $this -> hasOne(ChUser::class,'id','uid');
    }

    public function template()
    {
        return $this -> hasOne(ChSopTemplate::class,'id','template_id');
    }

    public static function  saveSop($uid,$mainUid,$data = [],$id = 0,$startDay=0)
    {
        $model = new self();
        if($id){
            $model = self::where('id',$id) -> first();
            if(empty($model)) throw new BusinessException(ErrorCode::NOT_ISSET,'数据不存在');
        }
        //查询模板信息
        $model -> uid = $uid;
        $model -> title = $data['title'];
        $model -> main_uid = $mainUid;
        $plan = [];

        $model -> corp_id = !empty($data['corp_id'])?$data['corp_id']:0;
        $model -> is_loop = !empty($data['is_loop'])?$data['is_loop']:0;
        $model -> template_id = $data['template_id'];
        $tempLateInfo = ChSopTemplate::query() -> where('id',$data['template_id']) -> first();
        $model -> template_type = $tempLateInfo -> template_type;
        $model -> is_return = $tempLateInfo -> is_return;
        $model -> return_code =  $tempLateInfo -> return_code;
        $model -> return_text =  $tempLateInfo -> return_text;

        $model -> auto_stop = !empty($data['auto_stop'])?$data['auto_stop']:0;
        $model -> is_track = data_get($data,'is_track',0);
        $model -> is_track  && $model -> track_limit = !empty($data['track_limit'])?$data['track_limit']:0;
        !empty($data['trigger_condition']) && $model -> trigger_condition = !is_array($data['trigger_condition'])?json_decode($data['trigger_condition']):$data['trigger_condition'];
        !empty($data['out_tag']) && $model -> out_tag = !is_array($data['out_tag'])?json_decode($data['out_tag']):$data['out_tag'];
        !empty($data['trigger_tag']) && $model -> trigger_tag = !is_array($data['trigger_tag'])?json_decode($data['trigger_tag']):$data['trigger_tag'];
        !empty($data['open_out_tag']) && $model -> open_out_tag = !is_array($data['open_out_tag'])?json_decode($data['open_out_tag']):$data['open_out_tag'];
        if(!is_array($data['plan'])){
            $data['plan'] = json_decode($data['plan'],true);
        }
        //标准模板
        if($tempLateInfo -> template_type == 1){
            $model -> send_type = $data['send_type'];
            if($data['send_type'] == 1){
                !empty($data['crowd_ids']) && $model -> crowd_ids = !is_array($data['crowd_ids'])?json_decode($data['crowd_ids']):$data['crowd_ids'];
                !empty($data['custom_ids']) && $model -> custom_ids = !is_array($data['custom_ids'])?json_decode($data['custom_ids']):$data['custom_ids'];
            }else{
                $model -> condition_conf = !is_array($data['condition_conf'])?json_decode($data['condition_conf']):$data['condition_conf'];
            }
            $model -> start_day = !empty($data['start_day'])?$data['start_day']:1;
            //标准模板为手动添加直接计算开始结束时间
            $startTime = datetime(strtotime("+".($data['plan'][0]['day']-1)." day"));
            if($startDay){
                foreach ($data['plan'] as $item){
                    if($startDay == $item['day']){
                        $startTime = datetime(strtotime("+".($item['day']-1)." day"));
                    }
                }
            }
            $endTime =  datetime(strtotime("+".($data['plan'][count($data['plan'])-1]['day']-1)." day"));
            $model->start_time=$startTime;
            $model->end_time=$endTime;
        }
        if($tempLateInfo -> template_type == 3){
            //存一个好友触发类型  优先级排序用
            $model -> tirgger_type = $model -> trigger_condition['tirgger_type'];
        }


        $plan = ChSopTemplate::formatConf($model -> template_type,$data['plan']);
        //$plan['send_type'] = $data['plan']['send_type'];
        foreach ($plan as &$p){
            $p['content'] = CommonService::formatMsgContent($p['content'])['content'];
        }
        $model -> plan = $plan;
        $model -> save();
        return $model;
    }


//    public static function bindRobot($sopIds = [],$robotIds = [])
//    {
//        self::query() -> whereIn('id',$sopIds) -> update(['robot_ids'=>json_encode($robotIds)]);
//    }
}
